package com.gitee.fsadmin.service.sys;

import com.gitee.fastmybatis.core.query.LambdaQuery;
import com.gitee.fastmybatis.core.util.TreeUtil;
import com.gitee.fsadmin.common.dto.StatusUpdateDTO;
import com.gitee.fsadmin.common.exception.BizException;
import com.gitee.fsadmin.common.support.ServiceSupport;
import com.gitee.fsadmin.common.util.CopyUtil;
import com.gitee.fsadmin.dao.entity.SysDept;
import com.gitee.fsadmin.dao.mapper.SysDeptMapper;
import com.gitee.fsadmin.service.sys.dto.SysDeptDTO;
import org.noear.solon.annotation.Component;

import java.util.List;
import java.util.Objects;


/**
 * @author 六如
 */
@Component
public class SysDeptService implements ServiceSupport<SysDept, SysDeptMapper> {

    public Long addDept(SysDept sysDept) {
        long count = this.query()
                .eq(SysDept::getParentId, 0)
                .getCount();
        if (count > 0 && Objects.equals(sysDept.getParentId(), 0L)) {
            throw new BizException("只能有一个根节点");
        }
        this.save(sysDept);
        return sysDept.getId();
    }

    public List<SysDeptDTO> listTree(LambdaQuery<SysDept> query) {
        List<SysDept> list = this.list(query);
        List<SysDeptDTO> sysDeptList = CopyUtil.copyList(list, SysDeptDTO::new);
        return TreeUtil.convertTree(sysDeptList, 0L);
    }


    /**
     * 修改状态
     *
     * @param statusUpdateDTO 修改值
     * @return 返回影响行数
     */
    public int updateStatus(StatusUpdateDTO statusUpdateDTO) {
        return this.query()
                .eq(SysDept::getId, statusUpdateDTO.getId())
                .set(SysDept::getStatus, statusUpdateDTO.getStatus())
                .update();
    }
}
